package model.tokens;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import state.TabState;
import state.TurtleState;

import model.expression.AbstractExpression;
import model.expression.command.AbstractCommandExpression;
import model.parser.Parser;
import model.parser.ParserException;
import model.parser.ParsingData;

import expression.Expression;

public class CommandToken extends AbstractToken {
	protected ParsingData myParsingData;

	public CommandToken(String value, ParsingData parsingData) {
		myParsingData = parsingData;
	}

	public ParsingData getParsingData() {
		return myParsingData;
	}
	
	@Override
	public void convertToPostFix(Stack<AbstractToken> opStack,
			Stack<AbstractExpression> outStack,TabState tabSt,Stack<AbstractExpression> out) {
		try {
			AbstractExpression newExpr;
			Class<?> exprClass = myParsingData.getExpressionClass();
			Constructor<?> constructor = exprClass.getConstructor(TabState.class);
			newExpr = (AbstractExpression) constructor.newInstance(tabSt);
			outStack.push(newExpr);
		} catch (Exception e) {
			throw ParserException.BAD_REFLECTION;
		}

		
	}
	
	
	@Override
	public AbstractExpression getExpression(TabState ts){
		AbstractExpression newExpr;
		try {
			Class<?> exprClass = myParsingData.getExpressionClass();
			Constructor<?> constructor = exprClass.getConstructor(TabState.class);
			newExpr = (AbstractExpression) constructor.newInstance(ts);
		} catch (Exception e) {
			throw ParserException.BAD_REFLECTION;
		}

		return newExpr;
}

	@Override
	public Stack<AbstractExpression> makeExpression(List<AbstractToken> toks,
			Stack<AbstractExpression> out, TabState tabSt,Parser temp) {
		Stack<AbstractExpression> outStack = new Stack<AbstractExpression>();
		AbstractExpression exp = toks.get(0).getExpression(tabSt);
		((AbstractCommandExpression) exp).addChildrenFrom(out);
		outStack.push(exp);	
		return outStack;
	}	

}
